const request = require("../../utils/request");

// pages/shoppingCart/shoppingCart.js
Page({

    /**
     * 页面的初始数据
     */
    data: {
        // 商品列表

        addressInfo:{},

        // 全选开关
        checkedAll: false,

        // 编辑开关
        editSwitch: false,

        //优惠明细弹窗
        isShowDiscount: false,

        location: null,

        list: [],
        listInfo: {},
        yoLikeList: [],
        page:1,
        isLastPage:false,

        allmoney: 0, //总价
        coupon_money: '', //优惠价

        cart_edit: false, //是否编辑
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {

    },
    onHide() {
        this.setData({
            cart_edit:false
        })
        getApp().globalData.rebuyIds = ''
        this.data.list.forEach(function (obj, index) {
            obj.checked = false
        })
    },
    onShow() {
        let location = wx.getStorageSync('localXiaoqu')
        this.setData({
            location,
            checkedAll: false,
            allmoney: 0
        })
        this.getList()
        this.getYouLike()
        getApp().getCartNum()
        this.getAddress()
    },
    onReachBottom(){
        if(this.data.isLastPage) {
            return
        }
        let page = this.data.page
        page++
        this.setData({
            page
        })
        this.getYouLike()

    },
    /**
     * 单个选择商品
     */
    checkboxChange(e) {
        const list = this.data.list;
        const index = e.currentTarget.dataset.index;
        list[index].checked = !list[index].checked;
        let checkedAll = true;
        for (let i = 0; i < list.length; i++) {
            if (!list[i].checked) {
                checkedAll = false;
                break;
            }
        }
        this.setData({
            list: list,
            checkedAll: checkedAll,
        });
        this.calcTotal()

    },
    /**
     * 选择全部
     */
    checkedAll() {
        const checkedAll = !this.data.checkedAll;
        const list = this.data.list;
        for (let i = 0; i < list.length; i++) {
            list[i].checked = checkedAll;
        }
        this.setData({
            list,
            checkedAll,
        });
        this.calcTotal()

    },

    /**
     * 显示删除商品按钮
     */
    changeEdit() {
        this.setData({
            cart_edit: !this.data.cart_edit
        })
    },
    /**
     * 加减
     */
    addNum(e) {
        let type = e.detail.type ? e.detail.type : e.currentTarget.dataset.type //1 减 2 加
        let item = e.detail.item ? e.detail.item : e.currentTarget.dataset.item
        let index = e.detail.index ? e.detail.index : e.currentTarget.dataset.index || 0
        const list = this.data.list;
        let _this = this
        if (type == 1) {
            if (item.nums == 1) {
                wx.showModal({
                    title: '提示',
                    content: '是否删除当前商品',
                    confirmColor: '#D12B2B',
                    success(res) {
                        if (res.confirm) {
                            // 购物车删除
                            request._get('/api?method=cart.del', {
                                ids: item.id
                            }).then(res => {
                                getApp().toast('删除成功')
                                getApp().getCartNum()
                                setTimeout(function () {
                                    _this.setData({
                                        list: []
                                    })
                                    _this.getList()
                                })
                            })
                        } else if (res.cancel) {
                        }
                    }
                })

                return
            }
            item.nums--
        } else {
          if(item.is_seckill && item.nums >= item.seckill_rule.max_nums){
            return getApp().toast('最多限购'+item.seckill_rule.max_nums+'件')
          }
            item.nums++
        }
        this.addCartApiCart(item, index)
        list[index] = Object.assign(list[index], item)
        this.setData({
          list
        })
        this.calcTotal()
    },
    //加减api
    addCartApiCart(item, index) {
      request._post('/api?method=cart.add', {
          product_id: item.product_id || item.id,
          nums: item.nums,
          num_type: 2,
      }, 'noload').then(res => {
          getApp().getCartNum()
          getApp().globalData.changePoint = true
          let list = this.data.list
          list[index].nums = item.nums
          wx.setStorageSync('cartList',list)
          this.setData({
              [`list[${index}]`]: list[index]
          })
      }).catch(res => {
          // 库存不足情况--
          let list = this.data.list
          list[index].nums--
          wx.setStorageSync('cartList',list)
          this.setData({
              [`list[${index}]`]: list[index]
          })

      })
  },
    // 计算总价
    calcTotal() {
        let list = this.data.list;
        let totalPrice = 0;
        let checkedAll = this.data.checkedAll
        list.forEach((item) => {
            if (item.checked === true) {
                console.log(parseInt(item.price))
                totalPrice +=(parseInt(item.price * 100) * Number(item.nums)) 
            } else if (checkedAll === true) {
                checkedAll = false;
            }
        });
        this.setData({
            checkedAll,
            allmoney: totalPrice /100
        })
    },
    // 批量删除
    delCartItem() {
        let ids = this.getSelected().join(',')
        let _this = this
        if (ids.length == 0) {
            return getApp().toast('请至少选择一件商品')
        }
        request._get('/api?method=cart.del', {
            ids
        }).then(res => {
            getApp().toast('删除成功')
            getApp().getCartNum()
            setTimeout(function () {
                _this.setData({
                    list: []
                })
                _this.getList()
            })
        })


    },
    // 获取选中的结果
    getSelected() {
        let list = this.data.list
        let arr = list.filter(el => el.checked)
        let ids = []
        arr.forEach(function (obj, index) {
            ids.push(obj.id)
        })
        return ids
    },
    // 获取猜你喜欢
    getYouLike() {
        let _this = this
        request._post('/api?method=goods.goodslist', {
            id: this.data.goods_id,
            page:this.data.page,
            limit:10,
            xiaoqu: wx.getStorageSync('localXiaoqu') ? wx.getStorageSync('localXiaoqu').id : ''
        }).then(res => {
            if(res.data.length == 0) {
                _this.setData({
                    isLastPage:true
                })
            } else {
                _this.setData({
                    isLastPage:false
                })
            }
            res.data.forEach(function (obj, index) {
              obj.addSwitch = false
              if (obj.cart_num) {
                  obj.addSwitch = true
              }
            })
            _this.setData({
                yoLikeList: _this.data.yoLikeList.concat(res.data)
            })
        })
    },

    // 选择当前配送点
    chooseLocation() {
        wx.navigateTo({
            url: '/pages/home/pages/my/peisongdian/peisongdian',
        })
    },
    /**
     * 优惠明细弹窗
     */
    showDiscount() {
        this.setData({
            isShowDiscount: true
        })
    },
    hideDiscount() {
        this.setData({
            isShowDiscount: false
        })
    },
    /**
     * 猜你喜欢详情
     */
    toDetail(e) {
        let item = e.currentTarget.dataset.item
        wx.navigateTo({
            url: '/pages/home/pages/my/product-details/product-details?id=' + item.goods_id,
        })
    },
    // 去添加商品
    toFirPage() {
        wx.switchTab({
            url: '/pages/index/index',
        })
    },
    /**
     * 加入购物车
     */

    add(e) {
      let item = e.detail.item ? e.detail.item : e.currentTarget.dataset.item
      let index = e.detail.index ? e.detail.index : e.currentTarget.dataset.index || 0
      let yoLikeList = this.data.yoLikeList
      if (!item.addSwitch) {
          item.addSwitch = true
          item.cart_num++
      }
      this.addCartApi(item, index)
      if(yoLikeList[index].product_id == item.id){
        yoLikeList[index].cart_num = item.cart_num
        yoLikeList[index].addSwitch = item.addSwitch
      }
      this.setData({
        yoLikeList
      })
  },
  // 购物车加减
  addCartReduce(e) {
      let type = e.currentTarget.dataset.type //1 减 2 加
      let item = e.currentTarget.dataset.item
      let index = e.currentTarget.dataset.index
      let yoLikeList = this.data.yoLikeList
      if (type == 1) {
          if (item.cart_num == 0) {
              // getApp().toast('商品不能再减了~')
              return
          }
          item.cart_num--
      } else {
          item.cart_num++
      }
      this.addCartApi(item, index)
      yoLikeList[index] = Object.assign(yoLikeList[index], item)
      this.setData({
        yoLikeList
      })
  },
  addCartApi(item, index) {
      request._post('/api?method=cart.add', {
          product_id: item.product_id || item.id,
          nums: item.cart_num,
          num_type: 2,
      }, 'noload').then(res => {
          getApp().getCartNum()
          this.getList()
      }).catch(res => {
          // 库存不足情况--
          let yoLikeList = this.data.yoLikeList
          yoLikeList[index].cart_num--
          if (yoLikeList[index].cart_num == 0) {
            yoLikeList[index].addSwitch = false
          }
          this.setData({
            [`yoLikeList[${index}]`]: yoLikeList[index]
          })
      })
  },

  /**
   * 输入框事件
   */
  bindManual: function (e) {
      var num = e.detail.value;
      this.setData({
          num: num
      });
  },
  getAddress(){
    request._post('/api?method=user.getusership', {}).then(res => {
      this.setData({
        addressInfo: res.data.find(el => el.is_def == 1),
      })
    })
  },
    // 获取购物车列表
    getList() {
        let _this = this
        request._post('/api?method=cart.cartlist', {
            xiaoqu: wx.getStorageSync('localXiaoqu') ? wx.getStorageSync('localXiaoqu').id : ''
            
        }).then(res => {
            let list = res.data.ori_goods_list
            let rebuyIds = getApp().globalData.rebuyIds ? getApp().globalData.rebuyIds.split(',') : []
            if (rebuyIds.length > 0) {
                rebuyIds = rebuyIds.map(Number)
            }
            wx.setStorageSync('cartList',list)
            _this.setData({
                list,
                listInfo: res.data
            })

            _this.data.list.forEach(function (obj, i) {
                if (rebuyIds.indexOf(obj.product_id) == 0 || rebuyIds.indexOf(obj.product_id) > 0) {
                    let e = {
                        currentTarget: {
                            dataset: {
                                index: Number(rebuyIds.indexOf(obj.product_id))
                            }
                        }
                    }
                    _this.checkboxChange(e)
                } else {
                    // obj.checked = true
                    _this.checkboxChange({
                        currentTarget: {
                            dataset: {
                                index:i
                            }
                        }
                    })
                 

                }
            })


        })
    },
    // 结算
    goToPay() {
        let ids = this.getSelected()
        if (ids.length == 0) {
            return getApp().toast('请至少选择一件商品')
        }
        wx.navigateTo({
            url: '/pages/home/pages/my/confirm-order/confirm-order?id=' + ids.join(',') + "&type=1",
        })
    }

})